<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j store-page-header component-common-header">
    <template v-if="headerData && headerData.length">
      <div
        class="store-signate-page-container"
        :style="config.bgUrl !== '' ? setBackground : 'background: #fff'"
      >
        <div class="store-singate-content">
          <div
            v-if="setTopShow"
            class="store-top"
          >
            <div
              class="top-logo"
              @click="handleLogoClick"
            >
              <img
                v-show="config.showLogo === 0"
                :src="webConfigData.pcLogoImgText"
                alt="图片加载失败"
              >
            </div>
            <div class="top-search">
              <div
                v-show="config.showSearch === 0"
                class="search-box"
              >
                <div
                  class="search-input"
                >
                  <input
                    v-model.trim="goodsText"
                    placeholder="输入商品名或店铺名"
                    @keyup.enter="searchGoods"
                  >
                  <div
                    class="search-types"
                    @click.stop="handleSearchItem"
                  >
                    <div class="types-name">
                      {{ searchItem === 0 ? '商品' : '店铺' }}
                    </div>
                    <img
                      src="@/assets/images/togger_icon.png"
                      alt=""
                    >
                  </div>
                  <div
                    class="search-btns"
                    @click="searchGoods"
                  >
                    搜索
                  </div>
                </div>
                <div
                  v-show="config.showHotWord === 0"
                  class="hot-word"
                >
                  <div class="con">
                    <span
                      v-for="(item, index) in hotSearchList"
                      :key="index"
                      class="item"
                      @click="searchHotKeyword(item.content)"
                    >{{ item.title }}</span>
                  </div>
                </div>
              </div>

              <div
                v-show="config.showSearch === 0"
                class="top-cart"
                @click="handleClickCart"
              >
                <span>购物车({{ cartNumberStore.cartNumbers > 99 ? '99+' : cartNumberStore.cartNumbers }})</span>
              </div>
            </div>
          </div>
          <div
            v-if="config.showNavs === 0"
            class="store-bottom"
          >
            <div
              v-if="config.showCategory === 0 && config.showNavs === 0"
              class="all-category"
              :style="{background: config.showCategory === 0 ? 'rgba(225, 37, 27, 1)' : 'none'}"
              @mouseenter="mouseEnter"
              @mouseleave="mouseLeave"
            >
              <span v-show="config.showCategory === 0">全部商品分类</span>
              <img
                v-show="config.showCategory === 0"
                src="@/assets/images/pc-category_icon.png"
                alt="图片加载失败"
              >
              <div
                v-show="isShowOne"
                class="menu-container"
              >
                <div
                  v-for="(item, index) in siderBar"
                  :key="index"
                  :class="{'menu-item': true, 'active': index === currentIndex}"
                  @click.stop="handleClickItems(item, index)"
                >
                  <span>{{ item.categoryName }}</span>
                  <img
                    v-if="currentIndex === index"
                    class="right_icon"
                    src="@/assets/images/c-arrow01.png"
                    alt=""
                  >
                  <img
                    v-else
                    class="right_icon"
                    src="@/assets/images/c-arrow02.png"
                    alt=""
                  >
                </div>
              </div>
              <!-- 每个item 对应的分类 start -->
              <div
                v-show="isshowDetail"
                class="menu-detail"
              >
                <div
                  v-for="(childItem, childIndex) in itemChildrenData"
                  :key="childIndex"
                  class="detail-items active"
                >
                  <div
                    class="detail_title"
                    @click="handleChildrenClick(childItem)"
                  >
                    <span>{{ childItem.categoryName }}</span>
                    <el-icon
                      class="el-icon-arrow-right detail_right_icon"
                    >
                      <ArrowRight />
                    </el-icon>
                  </div>
                  <div class="goods-content">
                    <template
                      v-for="(grandItem, grandIndex) in childItem.categories"
                      :key="grandIndex"
                    >
                      <div

                        class="goods-items"
                        @click="handleItem(grandItem)"
                      >
                        {{ grandItem.categoryName }}
                      </div>
                    </template>
                  </div>
                </div>
              </div>
              <!-- 每个item 对应的分类 end -->
            </div>
            <div
              v-show="config.showNavs === 0"
              :class="{'menu-content': true, 'isPadding': config.showCategory === 1}"
            >
              <template
                v-for="(item, index) in config.navList"
                :key="index"
              >
                <div

                  :class="item.menutState?'menu-items active':'menu-items'"
                  @click="handleRedirect(item)"
                >
                  {{ item.name }}
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </template>
    <!-- 登录弹窗组件 -->
    <login-popup
      v-if="showLogin"
      @hide-login-pop="hideLoginPop"
    />
    <!-- /登录弹窗组件 -->
  </div>
</template>
<script setup>
import Cookie from 'vue-cookies'
import { redirectPath } from '../common/pageConfig.js'
import * as util from '@/utils/index.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  otherHeader: { // 导航数据
    type: Array,
    default: () => []
  },
  categoryData: {
    type: Object,
    default: () => {
    }
  },
  // 首页装修数据
  pageRenovate: {
    type: Object,
    default: () => {
    }
  }
})

const siderBar = ref([]) // 侧边栏数据
watch(() => props.categoryData, (newVal) => {
  if (newVal.length > 0) {
    siderBar.value = newVal
  }
})

watch(() => props.pageRenovate, (newVal) => {
  headerData.value = []
  if (newVal) {
    if (newVal.content && Array.isArray(JSON.parse(newVal.content))) {
      JSON.parse(newVal.content).forEach(element => {
        if (element.type === 'shop_signs') {
          headerData.value.push(element)
        }
      })
      langStore.handleSetHeaders(headerData.value)
      config.value = {
        bgUrl: headerData.value[0].dataField.bgUrl,
        navList: headerData.value[0].dataField.navList,
        showCategory: headerData.value[0].dataField.showCategory,
        showLogo: headerData.value[0].dataField.showLogo,
        showNavs: headerData.value[0].dataField.showNavs,
        showSearch: headerData.value[0].dataField.showSearch,
        showHotWord: headerData.value[0].dataField.showHotWord
      }
    }
  } else {
    headerData.value = []
  }
  CheckRoute(route)
})

const route = useRoute()
const router = useRouter()
const langStore = useLanguageStore()
const cartNumberStore = useCartNumberStore()

const config = ref({
  bgUrl: '',
  navList: [],
  showCategory: 0,
  showLogo: 0,
  showNavs: 0,
  showSearch: 0,
  showHotWord: 0
})
const setBackground = computed(() => {
  // 设置导航背景
  return {
    background: `url(${config.value.bgUrl})`,
    'background-size': '100% 100%',
    'background-repeat': 'no-repeat'
  }
})

const setTopShow = computed(() => {
  const { showLogo, showSearch, bgUrl } = config.value
  return !(showLogo !== 0 && showSearch !== 0 && bgUrl === '')
})

// 设置头部数据
const setHeaderData = (arr) => {
  headerData.value = arr
  config.value = {
    bgUrl: arr[0].dataField.bgUrl,
    navList: arr[0].dataField.navList,
    showCategory: arr[0].dataField.showCategory,
    showLogo: arr[0].dataField.showLogo,
    showNavs: arr[0].dataField.showNavs,
    showSearch: arr[0].dataField.showSearch,
    showHotWord: arr[0].dataField.showHotWord
  }
  CheckRoute(route)
}

watch(() => route, (val) => {
  nextTick(() => {
    CheckRoute(val)
  })
}, {
  // 深度观察监听
  deep: true
})

const headerData = ref([]) // 头部数据
// 监听头部数据的变化
watch(() => props.otherHeader, (newVal) => {
  if (newVal.length > 0) {
    setHeaderData(newVal)
  } else {
    headerData.value = []
  }
}, { deep: true })

onMounted(() => {
  if (route.name !== 'index' && props.otherHeader && props.otherHeader.length === 0) { // 如果是其他页，并且父组件没有传头部过来，则让它去请求
    // getIndexData()
  } else if (props.otherHeader.length > 0) {
    // 如果父组件传递过来数据
    setHeaderData(props.otherHeader)
  }
  getHotSearchList(1) // 获取热搜列表
})

const webConfigStore = useWebConfigStore()
const webConfigData = computed(() => webConfigStore.pcConfig)

// 路由判断
const CheckRoute = (router) => {
  setMenuState(0)
  for (let navItem = 0; navItem < config.value.navList.length; navItem++) {
    const element = config.value.navList[navItem]
    if (element && element.path.link === '/') {
      if (router.path === '/index') {
        setMenuState(1, navItem)
        break
      }
    } else {
      if (element && element.path.link.toString().includes(router.path) && router.path !== '/') {
        setMenuState(1, navItem)
        break
      }
    }
  }
}

// 设置菜单状态 type:0 清除选中 type:1 添加选中
const setMenuState = (type, index) => {
  if (type === 0) {
    config.value.navList.forEach(nl => {
      nl.menutState = false
    })
  } else {
    config.value.navList[index].menutState = true
  }
}

// 获取侧边栏详情数据
const getDetailData = (id) => {
  return new Promise((resolve) => {
    http.get('/category/categoryInfo?parentId=' + id).then(({ data }) => {
      resolve(data.categoryInfo)
    })
  })
}

const isShowOne = ref(false) // 下拉菜单是否显示
// 鼠标移入
const mouseEnter = () => {
  isShowOne.value = true
  if (siderBar.value.length > 0) {
    handleClickItems(siderBar.value[0], 0)
  }
}

const currentIndex = ref('')
const itemChildrenData = ref([]) // 每个item对应的数据
const isshowDetail = ref(false) // 全部分类每个item是否显示
// 鼠标移除
const mouseLeave = () => {
  isShowOne.value = false
  currentIndex.value = ''
  isshowDetail.value = false
  itemChildrenData.value = []
}

let currentCategoryId = '' // 当前分类id
// 鼠标点击某个items
const handleClickItems = (item, index) => {
  currentCategoryId = item.categoryId
  currentIndex.value = index
  isshowDetail.value = true
  itemEnter(item, index)
}
// 防抖
const itemEnter = util._debounce((item) => {
  handleMouseEnter(item)
}, 100)

const handleMouseEnter = async (item) => {
  itemChildrenData.value = await getDetailData(item.categoryId)
}

const handleChildrenClick = () => {
  router.push({
    path: '/list',
    query: {
      cpid: currentCategoryId,
      cid: '',
      thCid: '',
      st: 0
    }
  })
}

// 菜单里面每个商品的跳转
const handleItem = (grandItem) => {
  router.push({
    path: '/list',
    query: {
      cpid: currentCategoryId,
      cid: grandItem.parentId,
      thCid: grandItem.categoryId,
      st: 0
    }
  })
}

// 菜单跳转
const handleRedirect = (item) => {
  if (item.path.type === '1') { // 链接的是商品
    const newPage = router.resolve({ path: '/detail', query: { prodId: item.path.link } })
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  } else {
    redirectPath(router, item)
  }
}

const goodsText = ref('') // 商品名称
const searchItem = ref(0)
// 搜索
const searchGoods = () => {
  if (goodsText.value === '') {
    if (searchItem.value === 0) {
      ElMessage({
        message: $t('commonHead.productNameCannotBeEmpty'),
        type: 'error',
        duration: 1000
      })
    } else {
      ElMessage({
        message: '店铺名称不能为空',
        type: 'error',
        duration: 1000
      })
    }
    return
  }
  // 跳转到商品列表页
  if (searchItem.value === 0) {
    router.push({
      path: '/list',
      query: {
        pn: goodsText.value
      }
    })
  } else {
    router.push({
      path: '/shop-list?',
      query: {
        shopName: goodsText.value
      }
    })
  }
}

// 点击搜索切换
const handleSearchItem = () => {
  if (searchItem.value === 0) {
    searchItem.value = 1
  } else {
    searchItem.value = 0
  }
  getHotSearchList(searchItem.value === 0 ? 1 : 2) // 获取热搜列表
}

const showLogin = ref(false) // 登录弹窗是否显示
// 购物车
const handleClickCart = () => {
  if (Cookie.get('bbcToken')) {
    router.push({
      path: '/cart'
    })
  } else { // 展示登录弹窗
    showLogin.value = true
  }
}
/**
     * 隐藏登录弹窗
     */
const hideLoginPop = () => {
  showLogin.value = false
  if (route.path.indexOf('user-center') > -1) {
    router.push({ path: '/' })
  }
}
// 点击logo
const handleLogoClick = () => {
  router.push({ path: '/' })
}

const hotSearchList = ref([]) // 热搜列表
/**
 * 获取热搜列表
 * @param {Number} type 1:商品 2:店铺
 */
const getHotSearchList = (type) => {
  http.get('/search/hotSearch', {
    params: {
      type
    }
  }).then(({ data }) => {
    hotSearchList.value = data.slice(0, 4)
  })
}

/**
 * 搜索热搜关键词
 * @param hotWord 热搜词语
 */
const searchHotKeyword = (hotWord) => {
  goodsText.value = hotWord
  searchGoods()
}

</script>
<style lang="scss" scoped>
@use "index";
</style>
